package com.lagou.rpc.provider;

import com.lagou.curator.ServerRegistryCenter;
import com.lagou.rpc.provider.server.RpcServer;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Scope;

/**
 * @ClassName: ServerBootstrapApplication
 * @Description:
 * @Author: qjc
 * @Date: 2021/9/21 10:45
 */
@SpringBootApplication
public class ServerBootstrapApplication2 implements CommandLineRunner, DisposableBean {

    @Autowired
    private RpcServer rpcServer;

    ServerRegistryCenter serverRegistryCenter = new ServerRegistryCenter();

    String ip = "127.0.0.1";
    int[] ports = new int[]{8898, 8899};


    public static void main(String[] args) {
        SpringApplication.run(ServerBootstrapApplication2.class, args);
    }

    @Override
    public void run(String... args) {
        for (int i = 0; i < ports.length; i++) {
            int port = ports[i];
            new Thread(() -> rpcServer.startServer(ip, port)).start();
            // 注册ip及端口信息
            serverRegistryCenter.register(ServerRegistryCenter.NODE_PREFIX + port, ip, port);
        }
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("应用关闭，删除节点");
        for (int port : ports) {
            serverRegistryCenter.deleteChildNode(ServerRegistryCenter.NODE_PREFIX + port);
        }
    }
}
